﻿using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Script.Serialization;
using Medora.Model;
using Medora.Model.Basic;
using Medora.Services;

namespace MvcApp.Controllers
{
    public class ControllerBase<T, F> : BaseApiController
        where T : DeletedEntity
        where F : IFilter
    {
        protected IService<T, F> _service;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        // GET api/<controller>
        public ControllerBase(IService<T, F> service)
        {
            _service = service;
        }

        [Route("GetByPage")]
        public IHttpActionResult GetByPage(int pageSize, int page, string filter, string ss)
        {
            
                var filterObj = serializer.Deserialize<F>(filter);
                SortInfo sort = null;
                if (!string.IsNullOrEmpty(ss)) sort = serializer.Deserialize<SortInfo>(ss);
                return Ok(_service.GetPaged(pageSize, page, filterObj, sort));
            
        }

        [Route("GetCount")]
        public IHttpActionResult GetCount()
        {
            return Ok(_service.GetCount());
            
        }

        // POST api/<controller>
        public IHttpActionResult Post([FromBody]T value)
        {
            if (ModelState.IsValid)
            {
                var userId = GetCurrentUserId();
                if (userId != null && userId != Guid.Empty)
                {
                    if (_service.Save(userId.Value, value)) return Ok(value);
                }
                return BadRequest("Authorization Error");
            }
            return BadRequest("Validation error");
        }

        // DELETE api/<controller>/5
        [HttpDelete]
        public IHttpActionResult Delete(string id)
        {
            var ids = serializer.Deserialize<List<Guid>>(id);
            if (_service.Delete(ids)) return Ok();
            return BadRequest("Error");
        }

    }
}